// mysql 数据库-示例
package main

import (
	"database/sql"
	"fmt"
	//"time"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	// user:password@tcp(localhost:5555)/dbname?charset=utf8
	db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/test?charset=utf8")
	checkErr(err)

	// insert
	stmt, err := db.Prepare("INSERT user_info SET username=?,departname=?,created=?")
	checkErr(err)

	res, err := stmt.Exec("astaxie", "研发部门", "2020-10-10")
	checkErr(err)

	id, err := res.LastInsertId()
	checkErr(err)

	fmt.Println("insert id:", id)

	// update
	stmt, err = db.Prepare("UPDATE user_info SET username=? WHERE uid=?")
	checkErr(err)

	res, err = stmt.Exec("astaxie update", id)
	checkErr(err)

	affect, err := res.RowsAffected()
	checkErr(err)

	fmt.Println("update:", affect)

	// select
	rows, err := db.Query("SELECT * FROM user_info")
	checkErr(err)

	for rows.Next() {
		var uid int
		var username string
		var department string
		var created string

		err = rows.Scan(&uid, &username, &department, &created)
		checkErr(err)

		fmt.Println("uid:", uid)
		fmt.Println("username:", username)
		fmt.Println("department:", department)
		fmt.Println("created:", created)
	}

	// delete
	stmt, err = db.Prepare("DELETE FROM user_info WHERE uid=?")
	checkErr(err)

	res, err = stmt.Exec(id)
	checkErr(err)

	affect, err = res.RowsAffected()
	checkErr(err)

	fmt.Println("delete:", affect)

	db.Close()
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

/*
go-sql-driver 定义的一些数据库链接和配置信息。它支持如下格式：

user@unix(/path/to/socket)/dbname?charset=utf8
user:password@tcp(localhost:5555)/dbname?charset=utf8
user:password@/dbname
user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname

db.Prepare()函数用来返回准备要执行的sql操作，然后返回准备完毕的执行状态。
db.Query()函数用来直接执行Sql返回Rows结果。
stmt.Exec()函数用来执行stmt准备好的SQL语句
*/